<?php
/**
 *
 * @Author nikm $
 *
 * @Date 2011-12-28 $
 */

if(!defined('FROM_INDEX')) exit('Invalid request');

function template($tpl)
{
	$tplFile = ROOT_PATH.'templates/'.TEMPLATE_STYLE.'/'.$tpl.'.html';
	$cacheFile = ROOT_PATH.'data/cache/templates/'.$tpl.'.php';
	
	clearstatcache();
	
	if(!is_file($cacheFile) || (@filemtime($tplFile) > @filemtime($fileName)))
	{
		if(!is_file($tplFile))
		{
			exit("Template file '".$tplFile."' does not exists!");
		}

		parse_template($tplFile, $cacheFile);
	}

	return $cacheFile;
}

function parse_template($tplFile, $cacheFile)
{
	$fp = @fopen($tplFile, 'r');
	$template = @fread($fp, filesize($tplFile));
	@fclose($fp);

	if(!$template)
	{
		exit('Template file "'.$tplFile.'" can not read!');
	}

	$var_regexp = "((\\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(-\>[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)?(\[[a-zA-Z0-9_\-\.\"\'\[\]\$\x7f-\xff]+\])*)";
	$const_regexp = "([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)";

	$template = preg_replace("/\<\!\-\-\{(.+?)\}\-\-\>/s", "{\\1}", $template);
	$template = preg_replace("/\{$var_regexp\}/s", "<?php echo \\1; ?>", $template);
	$template = preg_replace("/$var_regexp/es", "add_quote('<?php echo \\1; ?>')", $template);
	$template = preg_replace("/\<\?php echo \<\?php echo $var_regexp; \?\>; \?\>/es", "add_quote('<?php echo \\1; ?>')", $template);
	
	$template = preg_replace("/[\n\r\t]*\{eval\s+(.+?)\}[\n\r\t]*/ies", "strip_vtags('\n<?php \\1 ?>\n','')", $template);
	$template = preg_replace("/[\n\r\t]*\{echo\s+(.+?)\}[\n\r\t]*/ies", "strip_vtags('<?php echo \\1; ?>','')", $template);
	$template = preg_replace("/[\n\r\t]*\{elseif\s+(.+?)\}[\n\r\t]*/ies", "strip_vtags('<?php } elseif(\\1) { ?>','')", $template);
	$template = preg_replace("/[\n\r\t]*\{else\}[\n\r\t]*/is", "\n<?php } else { ?>", $template);
	
	for($i = 0; $i < 3; $i++)
	{
		$template = preg_replace("/[\n\r\t]*\{(?:sub)?templates?\s+[\"\']?([\w\d\-\_\.\:\/]+)[\"\']?\}/ies",'load_subtemplate("\\1")',$template);
		$template = preg_replace("/[\n\r\t]*\{loop\s+(\<\?[^\?]+?\?\>)\s+(\<\?[^\?]+?\?\>)\}[\n\r]*(.+?)[\n\r]*\{\/loop\}[\n\r\t]*/ies", "strip_vtags('\n<?php if(is_array(\\1)) { foreach(\\1 as \\2) { ?>','\n\\3\n<?php } } ?>\n')", $template);
		$template = preg_replace("/[\n\r\t]*\{loop\s+(\<\?[^\?]+?\?\>)\s+(\<\?[^\?]+?\?\>)\s+(\<\?[^\?]+?\?\>)\}[\n\r\t]*(.+?)[\n\r\t]*\{\/loop\}[\n\r\t]*/ies", "strip_vtags('\n<?php if(is_array(\\1)) { foreach(\\1 as \\2 => \\3) { ?>','\n\\4\n<?php } } ?>\n')", $template);
		$template = preg_replace("/[\n\r\t]*\{if\s+(.+?)\}[\n\r]*(.+?)[\n\r]*\{\/if\}[\n\r\t]*/ies", "strip_vtags('\n<?php if(\\1) { ?>','\n\\2\n<?php } ?>\n')", $template);
		$template = preg_replace("/[\n\r\t]*\{while\s+(.+?)\}[\n\r]*(.+?)[\n\r]*\{\/while\}[\n\r\t]*/ies", "strip_vtags('\n<?php while(\\1) { ?>','\n\\2\n<?php } ?>\n')", $template);
	}

	$template = preg_replace("/\{$const_regexp\}/s", "<?php echo \\1; ?>", $template);
	$template = '<?php /'.'* '.date('Y-m-d').' *'.'/ if(!defined("FROM_INDEX")) exit("Invalid request"); ?>'.$template;
	$template = trim($template);

	write_file($cacheFile, $template);
}

function write_file($fileName, $content)
{
	clearstatcache();

	$path = dirname($fileName);
	if(!is_dir($path))
	{
		mkdir($path, 0777, true);
	}

	$length = 0;
	if(function_exists('file_put_contents'))
	{
		$length = file_put_contents($fileName, $content);
	}
	else
	{
		$fp = @fopen($fileName, 'w');
		if($fp)
		{
			$length = fwrite($fp, $content);
			fclose($fp);
		}
		else
		{
			$length =  false;
		}
	}

	if(false === $length)
	{
		exit('Cache directory can not write!');
	}

	return $length;
}

function load_subtemplate($file)
{
	$tplFile = template($file);
	
	if($content = @implode('', file($tplFile)))
	{
		$content = str_replace('<?php /'.'* '.date('Y-m-d').' *'.'/ if(!defined("FROM_INDEX")) exit("Invalid request"); ?>', '', $content);
		
		return $content;
	}
	else
	{
		return '<!-- '.$file.' -->';
	}
}

function add_quote($var)
{
	return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $var));
}

function strip_vtags($expr, $statement)
{
	$expr = str_replace("\\\"", "\"", preg_replace("/\<\?php echo (\\\$.+?); \?\>/s", "\\1", $expr));
	$statement = str_replace("\\\"", "\"", $statement);
	return $expr.$statement;
}